import React, { useEffect, useState } from "react";
import { Card, InfiniteScroll, Empty, Ellipsis } from "antd-mobile";
import HeaderNav from "@/components/header-nav";
import FooterNav from "@/components/footer-nav";
import PageLoading from "@/components/page-loading";
import classNames from 'classnames';
import { showErrorToast } from '@/utils/customToast';
const { getNotifications, getUpdateUserInfo, getUserInfo } = $globalServicer('My');
const { setNotificationUnread } = $globalReduxAction('common');

import styles from "./index.module.less";

const Notifications = () => {
  const [list, setList] = useState([])
  const [page, setPage] = useState(1)
  const [loading, setLoading] = useState(false)
  const [initialLoading, setInitialLoading] = useState(true)
  const [hasMore, setHasMore] = useState(true)
  const [activeTab, setActiveTab] = useState('all') // 添加标签页状态

  // 标记通知为已读
  const markNotificationAsRead = async () => {
    try {
      // 只传递需要更新的字段，参考userInfo页面的做法
      const updateData = {
        is_read: 1
      }
      await getUpdateUserInfo(updateData)
      // 更新Redux状态，隐藏小红点
      setNotificationUnread(false)
    } catch (error) {
      console.error('标记通知为已读失败:', error)
    }
  }

  useEffect(() => {
    getList()
    // 进入系统通知页面时，标记通知为已读
    markNotificationAsRead()
  }, [])

  // 加载更多
  const loadMore = () => {
    const nextPage = page + 1;
    getList(nextPage)
  }

  // 获取通知列表数据
  const getList = (targetPage = 1) => {
    if (loading) return;

    setLoading(true)

    // 传递分页参数
    getNotifications(targetPage).then(res => {
      if (targetPage === 1) {
        // 第一页，替换数据
        setList(res.data)
      } else {
        // 后续页面，追加数据
        setList((prevData) => [...prevData, ...res.data])
      }
      
      setPage(targetPage)
      
      if (res.meta.pagination.current_page >= res.meta.pagination.total_pages) {
        setHasMore(false)
      }
    }).catch(err => {
      console.log(err)

      showErrorToast('通知获取失败');
    }).finally(() => {
      setLoading(false);
      // 初始加载完成后设置初始加载状态为 false
      if (targetPage === 1) {
        setInitialLoading(false);
      }
    })
  }

  // 通知类型字典
  const typeDesc = (type, item) => {
    let desc = "其他通知"
    switch (type) {
      case 'system_maintenance':
        desc = "系统维护通知"
        break;
      case 'new_character':
        desc = "新角色上线！"
        break;
      case 'welcome':
        desc = "欢迎来到智能体库！"
        break;
      case 'role_card_audit':
        desc = "智能体审核通知"
        break;
      case 'role_card_audit_failed':
        desc = "智能体审核通知"
        break;
      case 'user_creation':
        desc = item?.title || "用户创建通知"
        break;
      default:
        break;
    }
    return desc
  }

  // 格式化时间显示
  const formatTime = (dateString) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffTime = now - date;
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
    
    if (diffDays === 0) {
      return '今天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    } else if (diffDays === 1) {
      return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    } else if (diffDays < 7) {
      return `${diffDays}天前`;
    } else {
      return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
    }
  };

  // 过滤通知的函数
  const getFilteredNotifications = () => {
    if (activeTab === 'all') {
      return list;
    } else if (activeTab === 'system') {
      return list.filter(notification => notification.type !== 'user_creation');
    } else if (activeTab === 'official') {
      return list.filter(notification => notification.type === 'user_creation');
    }
    return list;
  };

  // 按日期分组通知
  const groupNotificationsByDate = (notifications) => {
    const groups = {};
    notifications.forEach(item => {
      const date = new Date(item.created_at);
      const dateKey = date.toDateString();
      if (!groups[dateKey]) {
        groups[dateKey] = [];
      }
      groups[dateKey].push(item);
    });
    return groups;
  };

  const filteredNotifications = getFilteredNotifications();
  const groupedNotifications = groupNotificationsByDate(filteredNotifications);

  // 如果正在初始化加载，显示 loading 页面
  if (initialLoading) {
    return <PageLoading />;
  }

  return (
    <div className={styles.page}>
      <HeaderNav title="系统通知" backArrow={false}></HeaderNav>
      
      <div className={styles.mainContent}>
        {/* 标签页导航 */}
        <div className={styles.tabContainer}>
          <button 
            className={classNames(styles.tab, { [styles.tabActive]: activeTab === 'all' })}
            onClick={() => setActiveTab('all')}
          >
            全部
          </button>
          <button 
            className={classNames(styles.tab, { [styles.tabActive]: activeTab === 'system' })}
            onClick={() => setActiveTab('system')}
          >
            系统通知
          </button>
          <button 
            className={classNames(styles.tab, { [styles.tabActive]: activeTab === 'official' })}
            onClick={() => setActiveTab('official')}
          >
            官方通知
          </button>
        </div>

        {/* 通知列表 */}
        {
          filteredNotifications.length > 0 ? (
            <div className={styles.notificationList}>
              {Object.entries(groupedNotifications).map(([dateKey, notifications]) => (
                <div key={dateKey} className={styles.dateGroup}>
                  <div className={styles.dateLabel}>
                    {formatTime(notifications[0].created_at)}
                  </div>
                  {notifications.map(item => (
                    <div key={item.id} className={styles.notificationCard}>
                      <h2 className={styles.notificationTitle}>{typeDesc(item.type, item)}</h2>
                      <div className={styles.notificationContent}>
                        <Ellipsis
                          className={styles.notificationText}
                          direction='end'
                          content={item.data}
                          expandText='展开'
                          collapseText='收起'
                        />
                      </div>
                    </div>
                  ))}
                </div>
              ))}
              <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
            </div>
          ) : <Empty style={{ marginTop: '200px' }} description='暂无通知' />
        }
      </div>
      <FooterNav />
    </div>
  )
}

export default Notifications;